package com.ellricky.baselib.ui.cla

import android.content.DialogInterface
import android.content.Intent
import android.view.View
import android.widget.Toast
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.andr.common.ui.activity.BaseToolBarActivity
import com.andr.common.ui.dialog.listener.OnSimpleAlertListener
import com.andr.common.ui.mvp.BasePresenter
import com.andr.common.util.EmptyUtil
import com.ellricky.baselib.BaseConstant
import com.ellricky.baselib.BaseConstant.RESULT_CODE_DEL
import com.ellricky.baselib.R
import com.ellricky.baselib.adapter.CommonGridItemDecoration
import com.ellricky.baselib.adapter.cla.StuModifyAdapter
import com.ellricky.baselib.adapter.cla.TcModifyAdapter
import com.ellricky.baselib.cache.LocalCacheUtil
import com.ellricky.baselib.entity.*
import com.ellricky.baselib.entity.new.ClassEntry
import com.ellricky.baselib.entity.new.MakeUp
import com.ellricky.baselib.entity.new.StudentEntry
import com.ellricky.baselib.entity.new.TeacherEntry
import com.ellricky.baselib.http.HttpUtils
import com.ellricky.baselib.listener.OnModifyListener
import com.ellricky.baselib.util.EAppUtil
import com.ellricky.baselib.util.EDialogUtil
import com.ellricky.baselib.util.NewEListCallback
import com.ellricky.baselib.util.NewEntityCallback
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.interfaces.OnSelectListener
import kotlinx.android.synthetic.main.base_activity_class_person_modify.*


private const val RV_STU_FIRST = 1
private const val RV_STU_SECOND = 2
private const val RV_TC_FIRST = 3
private const val RV_TC_SECOND = 4


/**
 * 班级管理：学员和老师修改信息页
 */
class PersonModifyActivity : BaseToolBarActivity<Void, BasePresenter<Void>>(), OnModifyListener {


    private var classNewEntity: ClassEntry? = null
    private lateinit var openDate: String
    private lateinit var classId: String
    private lateinit var courseListId: String

    private lateinit var stuFirstAdapter: StuModifyAdapter
    private lateinit var stuSecondAdapter: StuModifyAdapter

    private lateinit var tcFirstAdapter: TcModifyAdapter
    private lateinit var tcSecondAdapter: TcModifyAdapter

    private var curRvType: Int = -1
    private var curPos: Int = -1
    private var leaveId: String = ""

    private var resultCode = -5


    override fun getContentLayout() = R.layout.base_activity_class_person_modify

    override fun initUIView() {
        openDate = intent.getStringExtra("openDate") ?: ""
        classId = intent.getStringExtra("classId") ?: ""
        courseListId = intent.getStringExtra("course_list_id") ?: ""
        super.initUIView()
        mTvTitle.text = "修改信息"

        queryPerson()
    }


    private fun queryPerson() {
        val url = EAppUtil.getApiHost()
        val paramMap = hashMapOf<String, String>()
        paramMap["action"] = "classGradeDetail"
        paramMap["school_id"] = LocalCacheUtil.getSchoolId()
        paramMap["course_list_id"] = courseListId
        paramMap["eid"] = LocalCacheUtil.getUid()
        HttpUtils.getInstance()
            .postFrom(url, paramMap, object : NewEntityCallback<ClassEntry>(this) {
                override fun onSuccess(data: ClassEntry?, msg: String?) {
                    initPersonData(data)
                }
            })
    }

    private fun initPersonData(data: ClassEntry?) {
        classNewEntity = data
        classNewEntity?.let {
            rootView.visibility = View.VISIBLE
            when (it.class_classify) {
                "A" -> {
                    initRv(rvStuFirst, 3, RV_STU_FIRST)
                    initRv(rvTcFirst, 1, RV_TC_FIRST)
                    initRv(rvStuSecond, 6, RV_STU_SECOND)
                    initRv(rvTcSecond, 1, RV_TC_SECOND)
                }
                else -> {
                    secondRowView.visibility = View.GONE
                    initRv(rvStuFirst, 6, RV_STU_FIRST)
                    initRv(rvTcFirst, 1, RV_TC_FIRST)
                }
            }
        }
    }


    private fun initRv(rv: RecyclerView, spanCount: Int, rvType: Int) {
        val glm = object : GridLayoutManager(this, 3) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }

        rv.layoutManager = glm
        rv.addItemDecoration(CommonGridItemDecoration(this, spanCount, 0, false))
        rv.isNestedScrollingEnabled = false
//        attendRv.setHasFixedSize(true);

        when (rvType) {
            RV_STU_FIRST -> {
                stuFirstAdapter = StuModifyAdapter(this, rvType, this)
                rv.adapter = stuFirstAdapter
                stuFirstAdapter.refresh(initStuData(rvType))
            }
            RV_STU_SECOND -> {
                stuSecondAdapter = StuModifyAdapter(this, rvType, this)
                rv.adapter = stuSecondAdapter
                stuSecondAdapter.refresh(initStuData(rvType))
            }
            RV_TC_FIRST -> {
                tcFirstAdapter = TcModifyAdapter(this, rvType, this)
                rv.adapter = tcFirstAdapter
                tcFirstAdapter.refresh(initTcData(rvType))
            }
            else -> {
                tcSecondAdapter = TcModifyAdapter(this, rvType, this)
                rv.adapter = tcSecondAdapter
                tcSecondAdapter.refresh(initTcData(rvType))
            }
        }

    }

    private fun initStuData(rvType: Int): MutableList<StudentEntry> {
        val stuList = mutableListOf<StudentEntry>()

        val s1 = classNewEntity?.S_1 ?: mutableListOf()
        val s2 = classNewEntity?.S_2 ?: mutableListOf()

        classNewEntity?.let {
            when (it.class_classify) {
                "A" -> {
                    when (rvType) {
                        RV_STU_FIRST -> {
                            stuList.addAll(s1)
                            val emptyCount = 3 - stuList.size
                            for (i in 0 until emptyCount) {
                                stuList.add(StudentEntry("1"))
                            }
                        }
                        else -> {
                            stuList.addAll(s2)
                            val emptyCount = 3 - stuList.size
                            for (i in 0 until emptyCount) {
                                stuList.add(StudentEntry("2"))
                            }
                        }
                    }

                }
                else -> {
                    stuList.addAll(s1)
                    stuList.addAll(s2)
                    val emptyCount = 6 - stuList.size
                    for (i in 0 until emptyCount) {
                        stuList.add(StudentEntry("1"))
                    }
                }
            }
        }
        return stuList
    }

    private fun initTcData(rvType: Int): MutableList<TeacherEntry> {
        val tcList = mutableListOf<TeacherEntry>()

        val t1 = classNewEntity?.T_1
        val t2 = classNewEntity?.T_2

        classNewEntity?.let {
            when (it.class_classify) {
                "A" -> {
                    when (rvType) {
                        RV_TC_FIRST -> {
                            t1?.let { entity ->
                                tcList.add(entity)
                            } ?: let {
                                tcList.add(TeacherEntry("1"))
                            }
                        }
                        else -> {
                            t2?.let { entity ->
                                tcList.add(entity)
                            } ?: let {
                                tcList.add(TeacherEntry("2"))
                            }
                        }
                    }

                }
                else -> {
                    t1?.let { entity ->
                        tcList.add(entity)
                    } ?: let {
                        tcList.add(TeacherEntry("1"))
                    }
                }
            }
        }
        return tcList
    }

    override fun jumpStuAdd(rvType: Int, position: Int, sortNo: String) {
        curRvType = rvType
        curPos = position
        val intent = Intent(this, StuAddActivity::class.java)
        intent.putExtra("course_list_id", classNewEntity?.course_list_id)
        intent.putExtra("classId", classNewEntity?.class_id ?: "")
        intent.putExtra("sortNo", sortNo)
        EAppUtil.jumpForResult(this, intent)
    }


    override fun jumpTcAdd(rvType: Int, position: Int, sortNo: String) {
        curRvType = rvType
        curPos = position
        val intent = Intent(this, TeacherAddActivity::class.java)
        intent.putExtra("course_list_id", classNewEntity?.course_list_id)
        intent.putExtra("classId", classNewEntity?.class_id ?: "")
        intent.putExtra("sortNo", sortNo)
        EAppUtil.jumpForResult(this, intent)
    }

    override fun changeStatePerson(rvType: Int, position: Int, personId: String) {
        curRvType = rvType
        curPos = position

        var msg = ""

        val map = hashMapOf<String, String>()

        when (curRvType) {
            RV_STU_FIRST -> {
                showBottomPop("1", personId)
            }
            RV_STU_SECOND -> {
                showBottomPop("2", personId)
            }
            RV_TC_FIRST -> {
                msg = "确定删除该教师？"
                map["action"] = "gzaDeleteClassTeacher"
                map["teacher_user_id"] = personId
                map["class_grade_id"] = classId
                map["course_list_id"] = courseListId
                map["sort_no"] = "1"
                map["eid"] = LocalCacheUtil.getUid()
            }
            RV_TC_SECOND -> {
                msg = "确定删除该教师？"
                map["action"] = "gzaDeleteClassTeacher"
                map["teacher_user_id"] = personId
                map["class_grade_id"] = classId
                map["course_list_id"] = courseListId
                map["sort_no"] = "2"
                map["eid"] = LocalCacheUtil.getUid()
            }
        }
        if (EmptyUtil.isEmpty(msg)) return
        EDialogUtil.showDelConfirm(this, msg, object : OnSimpleAlertListener() {
            override fun onSure(dialogInterface: DialogInterface?) {
                super.onSure(dialogInterface)
                dialogInterface?.dismiss()
                delPerson(map)
            }
        })
    }

    private fun showBottomPop(sortNo: String, personId: String) {
        XPopup.Builder(this)
            .asBottomList(
                "请选择一项",
                arrayOf("上课", "请假", "旷课", "补课", "停课", "临时课", "删除")
            ) { _, text ->

                if (text == "删除") {
                    val map = hashMapOf<String, String>()
                    map["action"] = "gzaDeleteClassStudent"
                    map["student_member_id"] = personId
                    map["class_grade_id"] = classId
                    map["course_list_id"] = courseListId
                    map["sort_no"] = sortNo
                    map["eid"] = LocalCacheUtil.getUid()
                    delPerson(map)
                    return@asBottomList
                }

                if (text == "补课") {
                    getMakeUpList(personId)
                    return@asBottomList
                }
                changeStatus(text, personId)
            }.show()
    }

    private fun getMakeUpList(personId: String) {
        val url = EAppUtil.getApiHost()
        val map = hashMapOf<String, String>()
        map["action"] = "gzaLeaveLogList"
        map["member_id"] = personId
        map["school_id"] = LocalCacheUtil.getSchoolId()
        map["search_key"] = ""
        map["eid"] = LocalCacheUtil.getUid()
        HttpUtils.getInstance().postFrom(url, map, object : NewEListCallback<MakeUp>(this) {


            override fun onSuccess(data: MutableList<MakeUp>, msg: String?) {
                val list = data.map {
                    it.leave_date + "  " + it.leave_time + "  " + it.leave_desc
                }.toTypedArray()

                XPopup.Builder(this@PersonModifyActivity)
                    .asBottomList(
                        "请选择请假信息",
                        list
                    ) { position, text ->
                        val selectMakeup = data[position]
                        leaveId = selectMakeup.member_leave_id
                        changeStatus("补课", personId)
                    }.show()
            }
        })
    }

    private fun changeStatus(
        text: String?,
        personId: String
    ) {
        val map = hashMapOf<String, String>()
        val state = getJobStatus(text)
        map["action"] = "modifyStudentOutState"
        map["class_id"] = classId
        map["job_member_id"] = personId
        map["job_courselist_id"] = courseListId
        map["job_out_dic_id"] = state
        map["member_leave_id"] = leaveId
        map["eid"] = LocalCacheUtil.getUid()
        changeStatus(map)
    }

    private fun changeStatus(paramMap: Map<String, String>) {
        val url = EAppUtil.getApiHost()
        HttpUtils.getInstance().postFrom(url, paramMap, object : NewEntityCallback<Any>(this) {
            override fun onSuccess(var1: Any?, var2: String?) {
                leaveId = ""
                Toast.makeText(this@PersonModifyActivity, "修改成功", Toast.LENGTH_SHORT).show()
                resultCode = RESULT_CODE_DEL
                queryPerson()
            }
        })
    }

    private fun getJobStatus(text: String?): String {
        when (text) {
            "上课" -> return "5"
            "请假" -> return "6"
            "旷课" -> return "7"
            "补课" -> return "8"
            "停课" -> return "51"
            "临时课" -> return "61"
        }
        return ""
    }

    private fun delPerson(paramMap: Map<String, String>) {
        val url = EAppUtil.getApiHost()
        HttpUtils.getInstance().postFrom(url, paramMap, object : NewEntityCallback<Any>(this) {
            override fun onSuccess(var1: Any?, var2: String?) {
                resultCode = RESULT_CODE_DEL
                queryPerson()
            }
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (resultCode) {
            BaseConstant.RESULT_CODE_ADD -> {
                this.resultCode = resultCode
                queryPerson()
            }
        }
    }

    override fun onKeyBack(isKeyBack: Boolean) {
        if (resultCode > 0) {
            setResult(resultCode)
        }
        super.onKeyBack(isKeyBack)
    }
}